<template>
    <div>
        <div class="btnContainerBox">
            <template v-for="(btn,index) of localButtons">
                <template v-if="index < buttonCount-1 || index === localButtons.length - 1">
                    <div :class="{'bpm-task-button':true,'bpm-task-button-primary':JSON.parse(btn.style)}" :key="btn.id"
                         @click="btnClick(btn)">
                        <StarOutlined v-if="btn.id === 'btnTracked' && trackedTheme=='outlined'"
                                      :style="{'color':'#1890ff'}"/>
                        <StarFilled v-else-if="btn.id === 'btnTracked' && trackedTheme=='filled'"
                                    :style="{'color':'#eab207'}"/>
                        <rx-icon-show v-else-if="btn.icon" size="14px" :icon="getBtnIcon(btn.icon)"></rx-icon-show>
                        <span class="task-btn-name">{{ getI18Name(btn, 'name') }}</span>
                    </div>
                </template>
                <a-dropdown v-else-if="index == buttonCount-1">
                    <a class="ant-dropdown-link" @click="e => e.preventDefault()">
                        {{ $ti18('rxList.moreBtn', '更多') }}
                        <DownOutlined/>
                    </a>
                    <template #overlay>
                        <a-menu>
                            <template v-for="(innerBtn,index) of localButtons">
                                <a-menu-item v-if="index >= buttonCount-1 && index < localButtons.length - 1">
                                    <div :key="innerBtn.id" @click="btnClick(innerBtn)">
                                        <rx-icon-show v-if="innerBtn.icon" size="14px" :icon="getBtnIcon(innerBtn.icon)"></rx-icon-show>
                                        <span class="task-btn-name">{{ getI18Name(innerBtn, 'name') }}</span>
                                    </div>
                                </a-menu-item>
                            </template>
                        </a-menu>
                    </template>
                </a-dropdown>
            </template>
        </div>
        <a-modal :title="$ti18('rxMsa.actionTips','操作提示')" :cancelText="$ti18('rxForm.cancelBtn', '取消')"
                 :okText="$ti18('rxForm.ackBtn', '确认')" v-model:open="showPendStore" @ok="btnPendingOrRestore">
            <p v-if="visiableType=='pending'">{{ i18n('msa.pendingTips', '您确定要挂起当前任务吗？') }}</p>
            <p v-else-if="visiableType=='restore'">{{ i18n('msa.restoreTips', '您确定要恢复当前任务吗？') }}</p>
            <p>{{ i18n('taskCheck.opinion', '意见') }}</p>
            <p>
                <a-textarea v-model:value="opinion"></a-textarea>
            </p>
        </a-modal>
    </div>
</template>

<script>
import BpmtaskApi from "@/common/api/bpm/bpmTask";
import BpmInstApi from "@/common/api/bpm/bpmInst";
import BpmInstTrackedApi from "@/common/api/bpm/bpmInstTracked";
import {Util, RxIconShow} from "@lowcode/jpaas-base-lib";
import {App, BpmImageView} from '@lowcode/jpaas-share-component';
import BpmTaskCheck from "./task/BpmTaskCheck.vue";
import BpmTaskTransferCheck from "./task/BpmTaskTransferCheck.vue";
import BpmTaskBack from "./task/BpmTaskBack.vue";
import BpmTaskAddSign from "./task/BpmTaskAddSign.vue";
import BpmTaskTransferEdit from "./task/BpmTaskTransferEdit.vue";
import BpmTaskLinkup from "./task/BpmTaskLinkup.vue";
import BpmTaskRoam from "./task/BpmTaskRoam.vue";
import BpmTaskRoamTransfer from "./task/BpmTaskRoamTransfer.vue";
import TaskCommuReply from "../components/TaskCommuReply.vue";
import BpmInstStart from "./BpmInstStart.vue";
import FlowUtil from "../js/FlowUtil.js";
import taskButton from './js/taskButton.js';
import formBase from './js/formBase.js';

export default {
    name: "task-tool-bar",
    mixins: [formBase, FlowUtil, taskButton, App],
    components: {
        RxIconShow
    },
    props: {
        curData:{},
        bpmTaskDetail: {},
        taskConfig: {},
        canCommu: {
            default: true
        },
        bpmActionType: { type: String },
    },
    inject: ["broadCastChannel"],
    data() {
        return {
            btns: [],
            showDisCardBtn: false,
            isCanBack: false,
            isTransferRoam: false,
            isCanRoamTransfer: false,
            isRoamTransferLog: false,
            isBatch: false,
            addSignBtn: false,


            backOptions: [],
            canCheck: true,
            allowApprove: {},
            canTransfer: '',
            candicate: -1,
            lockStatus: "",
            //保存状态
            saveStatus: false,
            showPendStore: false,
            visiableType: "",
            opinion: "",


        }
    },
    computed: {
        //按钮数量
        buttonCount() {
            return this.taskConfig.maxButton || 5;
        },

        trackedTheme() {
            return this.bpmTaskDetail.tracked == '1' ? 'filled' : 'outlined';
        },
        trackText() {
            return this.bpmTaskDetail.tracked == "1" ? this.i18n('tooBar.btnTracked', '已跟踪') : this.i18n('tooBar.btnTrack', '跟踪');
        },
        showMoreOptions() {
            let taskShowMore = this.taskConfig.switchOptions.includes("showMoreOptions");
            if (taskShowMore) {
                return true;
            }
            let rtn = this.parentVm.processConfig.switchOptions.includes("showMoreOptions");

            return rtn;
        }
    },
    methods: {
        getBtnIcon(icon){
            try {
                let iconConfig = new Function(`return ${icon}`)();
                return iconConfig.icon
            }catch (e){
                return icon
            }
        },
        getI18Name(item) {
            if (item.i18nJson) {
                return this.$i18(item.i18nJson, item.name) || item.name;
            }
            return item.name;
        },
        btnClick(btn) {
            console.log(btn.method)
            if (!this.isBuildinBtn(btn.id)) {
                this.handMethod(btn)
            } else {
                this[btn['method']](btn)
            }
        },
        i18n(name, text, key) {
            return this.$ti18(name, text, "bpmTask", key);
        },
        isBuildinBtn(btn) {
            var btns = ['btnApprove', 'btnSave', 'btnLock', 'btnAddSign',
                'btnReject', 'btnTransfer', 'btnDiscard',
                'btnCommu', 'btnCommuInfo', 'btnReply', 'btnPrint'];
            return btns.indexOf(btn) > -1;
        },
        getCandicate() {
            if (!this.bpmTaskDetail.bpmTask || !this.bpmTaskDetail.bpmTask.hasCandicate) {
                this.candicate = -1;
                this.lockStatus = "";
                return;
            }
            //有侯选人
            if (this.bpmTaskDetail.bpmTask.assignee) {
                this.candicate = 1;
                this.lockStatus = this.i18n('lockStatus.taskStatus.releaseTask', '释放任务');
            } else {
                this.candicate = 2;
                this.lockStatus = this.i18n('lockStatus.taskStatus.lockTask', '锁定任务');
            }
        },
        doPrint() {
            var baseUrl = import.meta.env.JPAAS_BASE_URL;
            var bpmInst = this.bpmTaskDetail.bpmInst;
            var defId = bpmInst.defId;
            var instId = bpmInst.instId;
            var url = baseUrl;
            if(baseUrl.includes('main')){
                url += "/flowPrint/" + defId;
            }else {
                url += "/" + this.parentVm.appKey + "/flowPrint/" + defId;
            }
            if (instId) {
                url += "/" + instId;
            } else {
                url += "/-1";
            }
            let appId = this.curApp.appId;
            url += `?appId=${appId}`;
            window.open(url);
        },
        startSubProcess(alias) {
            var self_ = this;
            var formType = this.parentVm.processConfig.formType;
            var formData = {};
            if (formType == "online") {
                formData = this.rxForms.getData();
            }
            BpmInstApi.getSubProcessFormData({
                defKey: alias, mainDefId: this.parentVm.bpmTask.defId, instId: this.parentVm.instId, formData: formData
            }).then(res => {
                if (!res.success) {
                    return;
                }
                self_.startFlowPage(res.data);
            })
        },
        startFlowPage(data) {
            let self_ = this;
            Util.open({
                component: BpmInstStart,
                curVm: this,
                max: true,
                title: data.defName + this.i18n('startFlow.title', '流程启动'),
                data: {
                    defId: data.defId,
                    mainDefId: this.parentVm.bpmTask.defId,
                    mainTaskId: this.parentVm.bpmTask.actTaskId,
                    formData: data.formData,
                    vars: data.vars
                }
            }, function (action) {
                self_.broadCastChannel.postMessage({
                    type: "refreshTask",
                });
            });
        },
        //是否可以审批
        canApprove() {
            if (!this.allowApprove.success) {
                this.$message.warn(this.allowApprove.message);

            }
            return this.allowApprove.success;
        },
        approve() {
            if (!this.canApprove()) {
                return;
            }
            let quickApprove = this.taskConfig.switchOptions.includes("quickApprove");
            if (quickApprove) {
                this.confirmApprove();
            } else {
                this.approveTask();
            }
        },
        /**
         * 确认审批。
         */
        confirmApprove() {
            let self_ = this;
            this.$confirm({
                title: this.i18n('tooBar.tipInfo', '提示信息'),
                content: this.i18n('tooBar.confirmApprove', '确认审批吗?'),
                okText: this.$ti18('rxForm.ackBtn', '确认'),
                cancelText: this.$ti18('rxForm.cancelBtn', '取消'),
                onOk() {
                    self_.quickApprove();
                },
                onCancel() {
                },
            });
        },
        /**
         * 快速审批。
         * @returns {Promise<void>}
         */
        async quickApprove() {

            let parentVm = this.parentVm;
            if (parentVm.isCanRoamTransfer) {
                this.$message.error(this.i18n('taskCheck.isCanRoam', '当前任务正在流转，请取消流转后重试!'));
                return;
            }
            let res = await parentVm.$refs.rxForms.valid(true, "approve");
            if (!res.success) {
                return;
            }
            let data = this.getApproveData();

            let cmd = {
                taskId: data.taskId,
                checkType: "AGREE",
                opinion: "",
                formJson: data.formJson,
                systemHand: true,
                //幂等号
                idempotenceid: parentVm.idempotenceid
            }
            let self_ = this;
            BpmtaskApi.checkComplete(cmd).then(resp => {
                //发送消息通知其他地方刷新待办
                self_.broadCastChannel.postMessage({
                    type: "refreshTask",
                });


                if (parentVm.processConfig.formType == 'online') {
                    parentVm.$refs.rxForms.afterSubmit(resp, JSON.parse(data.formJson));
                }
                if (parentVm.isAlone) {
                    if (parentVm.destroy) {
                        Util.closeWindow(parentVm, "ok");
                    } else {
                        parentVm.loadTaskInfo();
                    }
                }
                //如果是使用统一URL的方式走下面的代码。
                else {
                    self_.reload();
                }

            })
        },
        getApproveData() {
            let self = this.parentVm;
            var data = {
                taskId: self.taskId,
                nodeExecutors: self.nodeExecutors,
                systemHand: true,
                taskConfig: this.taskConfig
            }
            let formData = {};
            if (self.processConfig.formType == "custom") {
                formData = this.customForm.getData();
                data.systemHand = false;
            }else if (self.processConfig.formType == "outsideUrl") {
                formData = this.outSideUrlForm.getData();
                data.systemHand = false;
            } else {
                formData = this.rxForms.getData();
                let opinionName = this.rxForms.getOpinionName();
                data.opinionName = opinionName;
            }

            let formJson = JSON.stringify(formData);
            data.formJson = formJson;
            //幂等号
            data.idempotenceid= self.idempotenceid;
            return data;
        },
        async valid(validRquired,action) {
            var res = { success: true }
            let formType = this.parentVm.processConfig.formType;
            //表单保存校验
            if (formType == 'custom') {
                res = await this.customForm.valid(validRquired,action);
                return res
            } else if (formType == 'outsideUrl') {
                res = await this.outSideUrlForm.valid(validRquired,action);
                return res
            } else {
                res = await this.rxForms.valid(validRquired, action);
                return res
            }
        },
        async approveTask() {
            let self = this.parentVm;
            if (self.isCanRoamTransfer) {
                this.$message.error(this.i18n('taskCheck.isCanRoam', '当前任务正在流转，请取消流转后重试!'));
                return;
            }
            let res = await this.valid(true, "approve");
            if (!res.success) {
              //  this.$message.warn(res.msg);
                return;
            }
            let data = this.getApproveData();

            //显示更多选项。
            data.showMoreOptions = this.showMoreOptions;
            let self_ = this;
            Util.open({
                component: !this.isTransferRoam ? BpmTaskCheck : BpmTaskTransferCheck,
                curVm: self,
                widthHeight: ['860px', '620px'],
                shade: true,
                title: self_.i18n('taskCheck.title', '任务审批'),
                data: data
            }, function (action) {

                //发送消息通知其他地方刷新待办
                self_.broadCastChannel.postMessage({
                    type: "refreshTask",
                });

                if (action == 'ok') {
                    //如果是独立打开的那么就关闭窗口。
                    if (self_.isAlone) {
                        if (self.destroy) {
                            Util.closeWindow(self, "ok");
                        } else {
                            self.loadTaskInfo();
                        }
                    }
                    //如果是使用统一URL的方式走下面的代码。
                    else {
                        self_.reload();
                    }
                } else if (action == "async") {
                    this.$router.push({
                        name: 'AccomplishBpm',
                        query: {appId: self_.curApp.appId}
                    })
                }
            });
        },
        addSign() {
            let self = this.parentVm;
            Util.open({
                component: BpmTaskAddSign,
                curVm: self,
                widthHeight: ['600px', '380px'],
                title: this.i18n('sign.title', '加签'),
                data: {
                    taskId: self.taskId
                }
            }, function (action) {
            });
        },
        getFormJson() {
            let self = this.parentVm;
            var formData = this.rxForms.getData();

            let formJson = JSON.stringify(formData);
            return formJson;
        },
        reject() {
            if (!this.canApprove()) {
                return;
            }
            let self_ = this;
            let self = this.parentVm;
            let formJson = this.getFormJson();
            var opinionName = this.rxForms.getOpinionName();
            Util.open({
                component: BpmTaskBack,
                curVm: self,
                widthHeight: ['860px', '490px'],
                title: this.i18n('rejectPage.title', '任务回退'),
                data: {
                    defId: this.bpmTaskDetail.bpmInst.defId,
                    instId: self.instId,
                    taskId: self.taskId,
                    formJson: formJson,
                    taskConfig: this.taskConfig,
                    isBatch: this.isBatch,
                    opinionName: opinionName
                }
            }, function (action) {
                if (action == 'ok') {
                    if (self.isAlone) {
                        Util.closeWindow(self, "ok");
                    } else {
                        self_.reload();
                    }
                }
            });
        },
        reload() {
            let parentVm = this.parentVm;
            let eventObj = {action: "inst", data: parentVm.instId};
            this.$bus.emit("flowEvent", eventObj);
        },
        doCancelRoamTransfer() {
            let self_ = this
            this.$confirm({
                title: self_.i18n('flowPage.cancelFlowTips', '确认取消流转任务吗？'),
                okText: this.$ti18('rxForm.ackBtn', '确认'),
                cancelText: this.$ti18('rxForm.cancelBtn', '取消'),
                zIndex: 999999,
                onOk() {
                    BpmtaskApi.cancelTransRoamTask(self_.parentVm.taskId).then(res => {
                        if (self_.isAlone) {
                            Util.closeWindow(self_.parentVm, "ok")
                        } else {
                            self_.reload();
                        }
                    })
                },
            });
        },
        roamInfo() {
            let self = this.parentVm;
            Util.open({
                component: BpmTaskRoam,
                curVm: self,
                widthHeight: ['800px', '450px'],
                title: this.i18n('flowPage.title', '任务流转'),
                data: {
                    taskId: self.taskId,
                    subject: self.bpmInst.subject,
                }
            }, function (action) {
                if (action == 'ok') {
                    self.loadTaskInfo();
                }
            });
        },
        doRoamTransfer() {
            if (!this.canApprove()) {
                return;
            }
            let self = this.parentVm;
            let this_ = this;
            Util.open({
                component: BpmTaskRoamTransfer,
                curVm: self,
                widthHeight: ['800px', '600px'],
                title: this_.i18n('flowPage.title', '任务流转'),
                data: {
                    taskId: self.taskId,
                    subject: self.bpmInst.subject,
                }
            }, function (action) {
                if (action == "ok") {
                    this_.doSaveData(function () {
                        if (self.isAlone) {
                            Util.closeWindow(self, "ok");
                        } else {
                            this_.reload();
                        }
                    });
                }
            });
        },
        doTransfer() {
            if (!this.canApprove()) {
                return;
            }
            let self = this.parentVm;
            let self_ = this;
            Util.open({
                component: BpmTaskTransferEdit,
                curVm: self,
                widthHeight: ['800px', '450px'],
                title: self_.i18n('transferPage.title', '任务转办'),
                data: {
                    taskId: self.taskId,
                    subject: self.bpmInst.subject,
                }
            }, function (action) {
                if (action == "ok") {
                    if (self.isAlone) {
                        Util.closeWindow(self, "ok");
                    } else {
                        self_.reload();
                    }
                }
            });
        },
        doDiscard() {
            if (!this.canApprove()) {
                return;
            }
            let self = this;
            let self_ = this.parentVm;
            this.$confirm({
                title: this.$ti18('rxMsa.actionTips', '操作提示'),
                content: self.i18n('msa.voidTips', '您确定作废当前任务吗？'),
                okText: this.$ti18('rxForm.ackBtn', '确认'),
                cancelText: this.$ti18('rxForm.cancelBtn', '取消'),
                zIndex: 20000,
                onOk() {
                    BpmInstApi.cancelProcess(self_.instId, "").then(res => {
                        if (self_.isAlone) {
                            Util.closeWindow(self_, "ok");
                        } else {
                            self.reload();
                        }
                    })
                },
                onCancel() {
                }
            })
        },
        doReplyCommu() {
            let self = this.parentVm;
            var taskId = this.bpmTaskDetail.bpmTask.taskId;
            let self_ = this;
            BpmtaskApi.canReplyCommu(taskId).then(res => {
                if (!res.success) {
                    return;
                }
                //回复沟通。
                Util.open({
                    component: TaskCommuReply,
                    curVm: self,
                    widthHeight: ['800px', '450px'],
                    title: self_.i18n('taskComm.replyComm', '回复沟通'),
                    data: {
                        taskId: self.taskId
                    }
                }, function (action) {
                    if (action == 'ok') {
                        if (self.isAlone) {
                            Util.closeWindow(self, "ok");
                        } else {
                            self_.reload();
                        }
                    }
                });
            })


        },
        communicate() {
            let self = this.parentVm;
            Util.open({
                component: BpmTaskLinkup,
                curVm: self,
                widthHeight: ['800px', '550px'],
                title: this.i18n('taskComm.taskComm', '任务沟通'),
                data: {
                    taskId: self.taskId,
                    subject: self.bpmInst.subject,
                }
            }, function (action) {
                if (action == 'ok') {
                    self.loadTaskInfo();
                }
            });
        },
        doRevoke() {
            let self = this.parentVm;
            //进行任务撤回处理
            BpmtaskApi.revokeCmTask(self.taskId).then(resp => {
                self.loadTaskInfo();
            });
        },

        async doSaveData(callback) {
            var self = this;
            this.saveStatus = true;
            let res = await this.valid(false, "save");
            if (!res.success) {
                this.saveStatus = false;
                //this.$message.warn(res.msg);
                return;
            }
            let data = {taskId: this.parentVm.taskId, systemHand: true};
            var formData = this.rxForms.getData();
            var formJson = JSON.stringify(formData);
            data.formJson = formJson;
            BpmtaskApi.saveFormData(data).then(resp => {
                self.saveStatus = false;
                if (self.parentVm.processConfig.formType != "custom" && self.parentVm.processConfig.formType != "outsideUrl") {
                    //表单保存时重新加载表单数据。
                    self.parentVm.loadTaskInfo();
                    self.rxForms.afterSubmit(resp, formData);
                }
                if (callback && typeof callback == 'function') {
                    callback();
                }
            });
        },
        doFlowImg() {
            let self = this.parentVm;
            let formData = this.rxForms.getData();
            Util.open({
                component: BpmImageView,
                curVm: self,
                widthHeight: ['1024px', '600px'],
                title: this.i18n('tooBar.btnFlowImg', '流程图'),
                data: {
                    taskId: self.taskId,
                    formData: formData,
                    preview: false
                }
            }, function (action) {
            });
        },
        doCommuHistory() {
            this.parentVm.bpmCommuShow = true;
        },
        doMessage() {
            this.parentVm.msgShow = true;
        },
        //更新任务的状态
        doLock() {
            let self = this.parentVm;


            let title = this.candicate == 1 ? this.i18n('msa.releaseTaskTips', '释放任务吗?') : this.i18n('msa.lockTaskTips', '锁定任务吗?');

            this.$confirm({
                title: this.$ti18('rxMsa.actionTips', '操作提示'),
                content: title,
                zIndex: 299999,
                okText: this.$ti18('rxForm.ackBtn', '确认'),
                cancelText: this.$ti18('rxForm.cancelBtn', '取消'),
                onOk() {
                    let data = {taskId: self.taskId};
                    BpmtaskApi.updateLocked(data).then(resp => {
                        self.loadTaskInfo();
                    });
                }
            })
        },
        commuInfo() {
            this.$emit("showBpmCommu");
        },
        doTracked() {
            let instId = this.bpmTaskDetail.bpmInst.instId;
            BpmInstTrackedApi.doTracked(instId).then(res => {
                this.bpmTaskDetail.tracked = res.data;
            })
        },
        //挂起或恢复 提示框
        showPendingMode(btn) {
            if (!this.canApprove()) {
                return;
            }
            let type = 'restore'; //默认 恢复时的参数；
            if (btn && btn.id == 'btnPending') {//挂起
                type = 'pending';
            }
            this.showPendStore = true;
            this.visiableType = type;
        },
        //挂起或恢复
        btnPendingOrRestore() {

            var taskId = this.bpmTaskDetail.bpmTask.taskId;
            let self_ = this;
            BpmtaskApi.taskPendingOrRestore(taskId, this.visiableType, this.opinion).then(res => {
                if (res.success) {
                    window.location.reload();
                }
            });
        },
    },
    watch: {
        bpmTaskDetail: {
            handler: function (val, oldval) {
                this.canCheck = val.canCheck;
                this.canTransfer = val.canTransfer;
                this.isCanBack = val.isCanBack;
                this.showDisCardBtn = val.isShowDiscardBtn;
                this.isTransferRoam = val.isTransferRoam;
                this.isCanRoamTransfer = val.isCanRoamTransfer;
                this.isRoamTransferLog = val.isRoamTransferLog;
                this.isBatch = val.isBatch;
                this.addSignBtn = val.canAddSign;
                this.allowApprove = val.allowApprove;
                this.backOptions = val.taskConfig.backOptions;
                //
                this.getCandicate();
            },
            deep: true
        },
        curData:{
            handler(data){
                let val = this.bpmTaskDetail ;
                this.btns = this.changeBtnHandle(this.bpmActionType,val,val.taskConfig.buttons,data);
            },
            deep: true
        }
    },
}
</script>

<style scoped>
.task-btn-name{
    margin-left: 4px;
}
.btnContainerBox {
    display: flex;
    align-items: center;
}

.bpm-task-button {
    height: 30px;
    line-height: 30px;
    padding: 0 12px;
    cursor: pointer;
}

.bpm-task-button:hover {
    color: #4285F4;
}

.bpm-task-button.bpm-task-button-primary {
    background-color: #4285F4;
    color: #fff;
    border-radius: 4px;
}

.ant-dropdown-link {
    padding: 0 12px;
}
</style>
